<template>
  <div class="allocation-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>分配记录管理</span>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="客户姓名">
              <el-input v-model="searchForm.customerName" placeholder="请输入客户姓名" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="分配状态">
              <el-select v-model="searchForm.status" placeholder="请选择分配状态" clearable style="width: 100%">
                <el-option label="待处理" value="pending" />
                <el-option label="已接受" value="accepted" />
                <el-option label="已拒绝" value="rejected" />
                <el-option label="已超时" value="expired" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="分配人">
              <el-select v-model="searchForm.allocatorId" placeholder="请选择分配人" clearable style="width: 100%">
                <el-option v-for="user in allocatorOptions" :key="user.id" :label="user.name" :value="user.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="被分配人">
              <el-select v-model="searchForm.assigneeId" placeholder="请选择被分配人" clearable style="width: 100%">
                <el-option v-for="user in assigneeOptions" :key="user.id" :label="user.name" :value="user.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="分配时间">
              <el-date-picker
                v-model="searchForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 批量操作 -->
      <div class="batch-actions">
        <el-button 
          type="danger" 
          @click="handleBatchDelete"
          :disabled="selectedRows.length === 0"
          :loading="batchDeleteLoading"
        >
          批量删除
        </el-button>
        <el-button 
          @click="handleExport"
          :loading="exportLoading"
        >
          导出记录
        </el-button>
      </div>

      <!-- 分配记录表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :max-height="tableHeight"
        class="responsive-table"
      >
        <el-table-column type="selection" width="55" fixed="left" />
        <el-table-column prop="customerName" label="客户姓名" min-width="120" fixed="left" />
        <el-table-column prop="status" label="分配状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="allocatorName" label="分配人" width="120" />
        <el-table-column prop="assigneeName" label="被分配人" width="120" />
        <el-table-column prop="allocationTime" label="分配时间" width="160" />
        <el-table-column prop="processTime" label="处理时间" width="160" />
        <el-table-column prop="remark" label="分配备注" min-width="150" show-overflow-tooltip />
        <el-table-column prop="processRemark" label="处理备注" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="handleView(row)">查看</el-button>
            <el-button 
              v-if="row.status === 'pending'" 
              type="text" 
              @click="handleProcess(row)"
            >
              处理
            </el-button>
            <el-button 
              type="text" 
              @click="handleManualAllocate(row)"
            >
              手动分配
            </el-button>
            <el-button type="text" @click="handleDelete(row)" style="color: #f56c6c">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination responsive-pagination"
      />
    </el-card>

    <!-- 处理分配对话框 -->
    <el-dialog
      v-model="processDialog.visible"
      title="处理分配"
      width="500px"
      class="responsive-dialog"
    >
      <el-form ref="processFormRef" :model="processDialog.form" :rules="processFormRules" label-width="100px">
        <el-form-item label="处理结果">
          <el-radio-group v-model="processDialog.form.result">
            <el-radio label="accept">接受</el-radio>
            <el-radio label="reject">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="处理备注" prop="remark">
          <el-input v-model="processDialog.form.remark" type="textarea" :rows="3" placeholder="请输入处理备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="processDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleProcessSubmit" :loading="processLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 手动分配对话框 -->
    <el-dialog
      v-model="manualDialog.visible"
      title="手动分配"
      width="500px"
      class="responsive-dialog"
    >
      <el-form ref="manualFormRef" :model="manualDialog.form" :rules="manualFormRules" label-width="100px">
        <el-form-item label="分配用户" prop="assigneeId">
          <el-select
            v-model="manualDialog.form.assigneeId"
            placeholder="请选择分配用户"
            filterable
            remote
            :remote-method="searchUsers"
            :loading="userLoading"
            style="width: 100%"
          >
            <el-option v-for="user in userOptions" :key="user.id" :label="user.name" :value="user.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="分配备注" prop="remark">
          <el-input v-model="manualDialog.form.remark" type="textarea" :rows="3" placeholder="请输入分配备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="manualDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleManualSubmit" :loading="manualLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 分配记录详情对话框 -->
    <el-dialog
      v-model="detailDialog.visible"
      title="分配记录详情"
      width="700px"
      class="responsive-dialog"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="客户姓名">{{ detailDialog.data.customerName }}</el-descriptions-item>
        <el-descriptions-item label="分配状态">
          <el-tag :type="getStatusType(detailDialog.data.status)">
            {{ getStatusLabel(detailDialog.data.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="分配人">{{ detailDialog.data.allocatorName }}</el-descriptions-item>
        <el-descriptions-item label="被分配人">{{ detailDialog.data.assigneeName }}</el-descriptions-item>
        <el-descriptions-item label="分配时间">{{ detailDialog.data.allocationTime }}</el-descriptions-item>
        <el-descriptions-item label="处理时间">{{ detailDialog.data.processTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="分配备注" :span="2">{{ detailDialog.data.remark || '无' }}</el-descriptions-item>
        <el-descriptions-item label="处理备注" :span="2">{{ detailDialog.data.processRemark || '无' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailDialog.data.createdTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailDialog.data.updatedTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import {
  getAllocationList,
  processAllocation,
  manualAllocate,
  deleteAllocation,
  exportAllocations,
  searchUsers
} from '@/api/crm'

// 表格数据
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])

// 搜索表单
const searchForm = reactive({
  customerName: '',
  status: '',
  allocatorId: '',
  assigneeId: '',
  dateRange: []
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 下拉选项
const allocatorOptions = ref([])
const assigneeOptions = ref([])
const userOptions = ref([])

// 加载状态管理
const processLoading = ref(false)
const manualLoading = ref(false)
const batchDeleteLoading = ref(false)
const exportLoading = ref(false)
const userLoading = ref(false)

// 表格高度计算
const tableHeight = computed(() => {
  const windowHeight = window.innerHeight
  return windowHeight - 350
})

// 表单引用
const processFormRef = ref<FormInstance>()
const manualFormRef = ref<FormInstance>()

// 对话框状态
const detailDialog = reactive({
  visible: false,
  data: {}
})

const processDialog = reactive({
  visible: false,
  currentId: '',
  form: {
    result: 'accept',
    remark: ''
  }
})

const manualDialog = reactive({
  visible: false,
  currentId: '',
  form: {
    assigneeId: '',
    remark: ''
  }
})

// 表单验证规则
const processFormRules: FormRules = {
  remark: [{ required: true, message: '请输入处理备注', trigger: 'blur' }]
}

const manualFormRules: FormRules = {
  assigneeId: [{ required: true, message: '请选择分配用户', trigger: 'change' }],
  remark: [{ required: true, message: '请输入分配备注', trigger: 'blur' }]
}

// 获取状态标签
const getStatusLabel = (status: string) => {
  const labels: Record<string, string> = {
    pending: '待处理',
    accepted: '已接受',
    rejected: '已拒绝',
    expired: '已超时'
  }
  return labels[status] || status
}

// 获取状态类型
const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    pending: 'warning',
    accepted: 'success',
    rejected: 'danger',
    expired: 'info'
  }
  return types[status] || 'info'
}

// 获取分配记录列表
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const res = await getAllocationList(params)
    tableData.value = res.rows
    pagination.total = res.total
  } catch (error) {
    ElMessage.error('获取分配记录列表失败')
  } finally {
    loading.value = false
  }
}

// 获取下拉选项
const fetchOptions = async () => {
  try {
    // 获取分配人和被分配人列表
    const res = await getAllocationList({ pageSize: 100 })
    const uniqueAllocators = Array.from(new Set(res.rows.map((item: any) => item.allocatorId)))
      .map(allocatorId => {
        const allocator = res.rows.find((item: any) => item.allocatorId === allocatorId)
        return { id: allocatorId, name: allocator.allocatorName }
      })
    const uniqueAssignees = Array.from(new Set(res.rows.map((item: any) => item.assigneeId)))
      .map(assigneeId => {
        const assignee = res.rows.find((item: any) => item.assigneeId === assigneeId)
        return { id: assigneeId, name: assignee.assigneeName }
      })
    allocatorOptions.value = uniqueAllocators
    assigneeOptions.value = uniqueAssignees
  } catch (error) {
    ElMessage.error('获取选项数据失败')
  }
}

// 搜索用户
const searchUsers = async (keyword: string) => {
  if (!keyword) return
  userLoading.value = true
  try {
    const res = await searchUsers({ keyword })
    userOptions.value = res
  } catch (error) {
    ElMessage.error('搜索用户失败')
  } finally {
    userLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    customerName: '',
    status: '',
    allocatorId: '',
    assigneeId: '',
    dateRange: []
  })
  handleSearch()
}

// 分页
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  fetchData()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  fetchData()
}

// 选择行
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows
}

// 查看详情
const handleView = async (row: any) => {
  try {
    const res = await getAllocationList({ id: row.id })
    detailDialog.data = res.rows[0]
    detailDialog.visible = true
  } catch (error) {
    ElMessage.error('获取分配记录详情失败')
  }
}

// 处理分配
const handleProcess = (row: any) => {
  processDialog.currentId = row.id
  processDialog.form = {
    result: 'accept',
    remark: ''
  }
  processDialog.visible = true
}

// 手动分配
const handleManualAllocate = (row: any) => {
  manualDialog.currentId = row.id
  manualDialog.form = {
    assigneeId: '',
    remark: ''
  }
  manualDialog.visible = true
}

// 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该分配记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteAllocation(row.id)
    ElMessage.success('删除分配记录成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) return
  
  batchDeleteLoading.value = true
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条分配记录吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const ids = selectedRows.value.map(row => row.id)
    await Promise.all(ids.map(id => deleteAllocation(id)))
    ElMessage.success('批量删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  } finally {
    batchDeleteLoading.value = false
  }
}

// 导出
const handleExport = async () => {
  exportLoading.value = true
  try {
    const blob = await exportAllocations(searchForm)
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `分配记录_${new Date().toLocaleDateString()}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  } finally {
    exportLoading.value = false
  }
}

// 提交处理
const handleProcessSubmit = async () => {
  if (!processFormRef.value) return
  
  await processFormRef.value.validate(async (valid) => {
    if (valid) {
      processLoading.value = true
      try {
        const params = {
          id: processDialog.currentId,
          action: processDialog.form.result,
          remark: processDialog.form.remark
        }
        await processAllocation(params)
        ElMessage.success('处理分配成功')
        processDialog.visible = false
        fetchData()
      } catch (error) {
        ElMessage.error('处理分配失败')
      } finally {
        processLoading.value = false
      }
    }
  })
}

// 提交手动分配
const handleManualSubmit = async () => {
  if (!manualFormRef.value) return
  
  await manualFormRef.value.validate(async (valid) => {
    if (valid) {
      manualLoading.value = true
      try {
        const params = {
          id: manualDialog.currentId,
          assigneeId: manualDialog.form.assigneeId,
          remark: manualDialog.form.remark
        }
        await manualAllocate(params)
        ElMessage.success('手动分配成功')
        manualDialog.visible = false
        fetchData()
      } catch (error) {
        ElMessage.error('手动分配失败')
      } finally {
        manualLoading.value = false
      }
    }
  })
}

// 初始化
onMounted(() => {
  fetchData()
  fetchOptions()
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    // 表格高度会自动重新计算
  })
})
</script>

<style scoped lang="scss">
.allocation-management {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
  }

  .search-form {
    margin-bottom: 20px;
  }

  .batch-actions {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  // 响应式设计
  @media screen and (max-width: 768px) {
    .card-header {
      flex-direction: column;
      align-items: flex-start;
    }

    .batch-actions {
      justify-content: center;
    }

    .pagination {
      justify-content: center;
    }
  }

  @media screen and (max-width: 480px) {
    .search-form {
      .el-form-item {
        margin-bottom: 10px;
      }
    }

    .batch-actions {
      .el-button {
        margin-bottom: 5px;
      }
    }
  }
}

// 全局响应式样式
.responsive-table {
  :deep(.el-table__header) {
    th {
      background-color: #f5f7fa;
      font-weight: 600;
    }
  }
}

.responsive-pagination {
  :deep(.el-pagination__sizes) {
    @media screen and (max-width: 768px) {
      display: none;
    }
  }
}

.responsive-dialog {
  @media screen and (max-width: 768px) {
    :deep(.el-dialog) {
      width: 95% !important;
      margin-top: 10vh !important;
    }
  }
}
</style>